package cn.edu.swu.picture;


import cn.edu.swu.core.BasicServlet;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload2.core.DiskFileItemFactory;
import org.apache.commons.fileupload2.core.FileItem;
import org.apache.commons.fileupload2.jakarta.servlet6.JakartaServletFileUpload;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.sql.*;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

//接受http请求,提取参数，转给service，完成相应的功能，结果返回html网页
//只有这个类和web有关
//@WebServlet(urlPatterns = "/picture/*")
public class PictureController extends  BasicServlet{

    private PictureService pictureService = null;

    // 上传文件存储目录
    private static final String UPLOAD_DIRECTORY = "upload";

    // 上传配置
    private static final int MEMORY_THRESHOLD   = 1024 * 1024 * 3;  // 3MB
    private static final int MAX_FILE_SIZE      = 1024 * 1024 * 40; // 40MB
    private static final int MAX_REQUEST_SIZE   = 1024 * 1024 * 50; // 50MB


    //
    public void init(ServletConfig config){
        PictureRepo repo = new PictureRepo();
        pictureService = new PictureService();
        pictureService.setRepo(repo);
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.methodRoute(request,response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        this.methodRoute(request,response);
    }

    private void methodRoute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取路径
        String uri = request.getRequestURI();
        System.out.println(uri);
        String method = uri.substring(uri.lastIndexOf("/") + 1);

        try {
            if(method.equals("list")){
                this.list(request,response);
            }else if(method.equals("add")){
                this.add(request, response);
            } else if (method.equals("delete")) {
                this.delete(request, response);
            } else if (method.equals("edit")) {
                this.edit(request, response);
            }else if(method.equals("update")){
                this.update(request, response);
            } else if (method.equals("search")) {
                this.search(request,response);
            }
        }catch (IOException | SQLException e) {
            throw new ServletException(e);
        }

        response.sendRedirect("./list");
    }






    public void list(HttpServletRequest request, HttpServletResponse response) throws ServletException{
        //取出pictures,然后返回html的table(即返回给用户显示出来)
        try {
            List<Picture> pictures = this.pictureService.getAll();
            //获得的只是数据，要转换为html代码写出来给客户，调用tohtml写出来
            try(Writer writer = response.getWriter()){
                String table = this.toHtmlTable(pictures);
                String page = this.warpHtmlPage(table);
                writer.write(page);
            }
        } catch (SQLException | IOException e) {
            throw new ServletException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }



    public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {



        if (!JakartaServletFileUpload.isMultipartContent(request)) {
            // 如果不是则停止
            Writer writer = response.getWriter();
            writer.write("Error: 表单必须包含 enctype=multipart/form-data");
            writer.flush();
            return;
        }


        // 配置上传参数
        DiskFileItemFactory factory = DiskFileItemFactory
                .builder()
                .setBufferSize(MEMORY_THRESHOLD)
                .get();
        // 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中
//        factory.setSizeThreshold(MEMORY_THRESHOLD);
        // 设置临时存储目录
//        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

        JakartaServletFileUpload upload = new JakartaServletFileUpload(factory);

        // 设置最大文件上传值
        upload.setFileSizeMax(MAX_FILE_SIZE);

        // 设置最大请求值 (包含文件和表单数据)
        upload.setSizeMax(MAX_REQUEST_SIZE);

        // 中文处理
        upload.setHeaderCharset(Charset.forName("UTF-8"));

        // 构造临时路径来存储上传的文件
        // 这个路径相对当前应用的目录
        String uploadPath = request.getServletContext().getRealPath("./") + File.separator + UPLOAD_DIRECTORY;

        // 如果目录不存在则创建
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }

        Picture picture = new Picture();

        try {

            String imageName = UUID.randomUUID().toString();
            // 解析请求的内容提取文件数据
            @SuppressWarnings("unchecked")
            List<FileItem> formItems = upload.parseRequest(request);

            if (formItems != null && formItems.size() > 0) {
                // 迭代表单数据
                for (FileItem item : formItems) {
                    // 处理不在表单中的字段
                    if (!item.isFormField()) {
                        String image = new File(item.getName()).getName();
                        imageName += image.substring(image.lastIndexOf("."));
                        String filePath = uploadPath + File.separator + imageName;
                        File storeFile = new File(filePath);
                        // 在控制台输出文件的上传路径
                        System.out.println(filePath);
                        // 保存文件到硬盘
                        item.write(storeFile.toPath());

                        picture.setImage(imageName);
//                        request.setAttribute("message",
//                                "文件上传成功!");
                    }else{
                        if(item.getFieldName().equals("type")){
                            picture.setType(item.getString());
                        }else if(item.getFieldName().equals("DOL")){
                            picture.setDOL(item.getString());
                        }else if(item.getFieldName().equals("memo")){
                            picture.setMemo(item.getString());
                        }else if(item.getFieldName().equals("store")){

                            try {
                                picture.setStore(pictureService.simpleDateFormat.parse(item.getString()));
                            } catch (ParseException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }


//        接受用户参数后交给picture service,service再把他封装成picture,保存到数据库里面
        try {
            this.pictureService.save(picture);
        } catch (SQLException e) {
            throw new ServletException(e);
        }

    }
    //        String type = request.getParameter("type");
//        String DOL = request.getParameter("DOL");
//        String memo = request.getParameter("memo");
//        String store = request.getParameter("store");



    public void delete(HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException {
        int id = Integer.parseInt(request.getParameter("id"));
        this.pictureService.deleteById(id);
    }

    private void edit(HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException, ServletException {
        int id = Integer.parseInt(request.getParameter("id"));
        //先获得这本书,在repo中写方法,在service中添加服务，最后在这里的使用
        try {
            Picture picture = this.pictureService.getById(id);
            //获得的只是数据，要转换为html代码写出来给客户，调用tohtml写出来
            try(Writer writer = response.getWriter()){
                String form = this.wrapEditForm(picture);
                String page = this.warpHtmlPage(form);
                writer.write(page);
            }
        } catch (SQLException | IOException e) {
            throw new ServletException(e);
        }
    }

//    private void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
//        int id = Integer.parseInt(request.getParameter("id"));
//        String type = request.getParameter("type");
//        String DOL = request.getParameter("DOL");
//        String memo = request.getParameter("memo");
//        String store = request.getParameter("store");
//        String image = request.getParameter("image");
//        //接受用户参数后交给picture service,service再把他封装成picture,保存到数据库里面
//        try {
//            this.pictureService.update(id,type,DOL,memo,store,image);
//        } catch (SQLException e) {
//            throw new ServletException(e);
//        }
//    }

    private void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        this.add(request, response);
    }

    private void search(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String key =(request.getParameter("key"));
        try {
            List<Picture> pictures = this.pictureService.search(key);
            try(Writer writer = response.getWriter()){
                String table = this.toHtmlTable(pictures);
                String page = this.warpHtmlPage(table);
                writer.write(page);
            }
        } catch (SQLException | IOException e) {
            throw new ServletException(e);
        }

    }


    //这里写返回的htmlTable
    private String toHtmlTable(List<Picture> pictures){
        StringBuilder sb = new StringBuilder();
        sb.append("<table class='lps'>\n");
        sb.append("<tr><th>编号</th><th>类型</th><th>喜爱程度</th><th>描述</th><th>收藏日期</th><th>图片</th><th></th><th></th></tr>");
        for(Picture picture:pictures){
            sb.append("<tr>");
            sb.append("<td class='center'>").append(picture.getId()).append("</td>");
            sb.append("<td>").append(picture.getType()).append("</td>");
            sb.append("<td>").append(picture.getDOL()).append("</td>");
            sb.append("<td>").append(picture.getMemo()).append("</td>");
            sb.append("<td class='center'>").append(picture.getStore()).append("</td>");
            sb.append("<td class='center'> <img class='picture-img-thumbnail' src='../upload/").append(picture.getImage()).append("'/></td>");
            sb.append("<td class='center'><a href='./delete?id=" + picture.getId() +"'>删除</a></td>");
            sb.append("<td class='center'><a href='./edit?id=" + picture.getId() +"'>修改</a></td>");
            sb.append("</tr>");
        }
        sb.append("</table>");

        return sb.toString();
    }

    //包装一个表单
    private String wrapEditForm(Picture picture){
        StringBuilder sb = new StringBuilder();
        sb.append("<center><br>")
                .append("<form action='./update?id="+ picture.getId() +"' method=\"post\" enctype=\"multipart/form-data\">")
                .append("<input type=\"hidden\" name=\"type\" value=\"" + picture.getId() + "\"<br><br>")
                .append("类型:<input type=\"text\" name=\"type\" value=\"" + picture.getType() + "\"<br><br>")
                .append("喜爱:<input type=\"text\" name=\"DOL\" value=\"" + picture.getDOL() + "\"><br><br>")
                .append("描述:<input type=\"text\" name=\"memo\" value=\"" + picture.getMemo() + "\"><br><br>")
                .append("日期:<input type=\"text\" name=\"store\" value=\"").append(picture.getStore()).append("\"><br><br>")
                .append("图片:<input type=\"file\" name=\"image\" ").append("\"><br><br>")
                .append("<input type=\"submit\" name=\"submit\" value=\"确认修改\">")
                .append("</form>")
                .append("</center>");
        return sb.toString();
    }

    //连接数据库
    public Connection getConnection() throws SQLException, ClassNotFoundException {
        Class.forName("com.mysql.cj.jdbc.Driver");
        //jdbc协议下连接mysql,地址为本机，再接上数据库名字
        String jdbcUrl = "jdbc:mysql://127.0.0.1:3306/landscapepictures";
        String dbUser  = "root";
        String dbPass  = "159357";
        Connection connection = DriverManager.getConnection(jdbcUrl,dbUser,dbPass);
        return connection;
    }

    //查询并取出
    private List<Picture> getAllPictures () throws SQLException, ClassNotFoundException {
        List<Picture> pictures = new ArrayList<>();
        //建立数据库的连接
        try (Connection connection = this.getConnection()) {
            //创建一个访问数据库的陈述
            try (Statement statement = connection.createStatement()) {
                //查询
                String sql = "SELECT * FROM picture";
                ResultSet rs = statement.executeQuery(sql);
                //用while循环逐条取出每条数据
                while (rs.next()) {
                    Picture pi = new Picture();
                    pi.setId(rs.getInt("id"));
                    pi.setType(rs.getString("Type"));
                    pi.setDOL(rs.getString("DOL"));
                    pi.setMemo(rs.getString("memo"));
                    pi.setStore(rs.getDate("store"));
                    pi.setImage(rs.getString("image"));
                    //每个picture都依次添加进去
                    pictures.add(pi);
                }
            }
        }

        return pictures;
    }


}

